package com.jjc.android.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.adapter.MyDeviceAdapter
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.ChangeDeviceEvent
import com.jjc.android.entity.DeviceDto
import com.jjc.android.entity.KeyValuePair
import com.jjc.android.entity.LzyResponse
import com.jjc.android.entity.PageInfo
import com.jjc.android.entity.ProductManualDto
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.ComplexSpannableStringUtils
import com.jjc.android.util.NoRefCopySpan
import com.jjc.android.util.SimpleOnRefreshLoadMoreListener
import com.jjc.android.util.paramEx
import com.jjc.android.view.CommonKt.appendDeviceName
import com.jjc.android.view.onClick
import com.lzy.okgo.OkGo
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.zerobranch.layout.SwipeLayout
import io.reactivex.Observable
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MyDeviceActivity : BaseActivity(){

    override val layoutId: Int = R.layout.activity_operation_video
    private val smartRefreshLayout: SmartRefreshLayout by lazy { findViewById<SmartRefreshLayout>(R.id.smartRefreshLayout) }
    private val recyclerView: RecyclerView by lazy { findViewById<RecyclerView>(R.id.recyclerView) }
    private val homeBtn: ImageView by lazy { findViewById(R.id.homeBtn) }
    private lateinit var mAdapter:MyDeviceAdapter
    private val refreshLayoutDelegate by lazy {
        object : SimpleOnRefreshLoadMoreListener(){
            override fun invokeActivity(block: BaseActivity.() -> Unit) {
                this@MyDeviceActivity.apply(block)
            }

            override fun loadPage(
                page: Int,
                actionSuccess: (Int, List<Any>?) -> Unit,
                actionError: (Int, String?) -> Unit
            ) {
                OkGo.post<LzyResponse<PageInfo<DeviceDto>>>(Constants.getFormList)
                    .paramEx(mutableMapOf("page" to page.toString(),"pagesize" to Constants.PAGE_SIZE.toString(),"needpage" to "1","formheaduuid" to "2582bc4c14914246807a26886f46dd0e","isasc" to true,
                        "sortid" to "created_at","filters" to listOf<KeyValuePair>(
                        KeyValuePair("ope0wk2ysioftswt",UserManager.userId())
                    )),true)
                    .tag(this)
                    .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<DeviceDto>>>(false){
                        override fun onCallSuccess(response: LzyResponse<PageInfo<DeviceDto>>) {
                            if(response.data?.data.isNullOrEmpty()){
                                actionSuccess.invoke(page,response.data?.data)
                                return
                            }
                            actionSuccess.invoke(page,response.data?.data)
//                            response.data?.data?.map { device->
//                                Observable.create<DeviceDto>{emitter->
//                                    OkGo.post<LzyResponse<PageInfo<DeviceDto>>>(Constants.getFormList)
//                                        .paramEx(mutableMapOf("page" to page.toString(),"pagesize" to Constants.PAGE_SIZE.toString(),"needpage" to "1","formheaduuid" to "2582bc4c14914246807a26886f46dd0e","filters" to listOf<KeyValuePair>(
//                                            KeyValuePair("bhmohipntdlpc61m",device.bhmohipntdlpc61m)
//                                        )),true)
//                                        .tag(this)
//                                        .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<DeviceDto>>>(false){
//                                            override fun onCallSuccess(response: LzyResponse<PageInfo<DeviceDto>>) {
//                                                device.accounts = response.data?.data
//                                                emitter.onNext(device)
//                                                emitter.onComplete()
//                                            }
//
//                                            override fun onCallError(error: String?) {
//                                                super.onCallError(error)
//                                                emitter.onNext(device)
//                                                emitter.onComplete()
//                                            }
//                                        })
//                                }
//                            }.let {
//                                Observable.zip(it){
//                                    it
//                                }
//                            }
//                                .subscribe({
//                                    actionSuccess.invoke(page,response.data?.data)
//                                },{
//                                    actionSuccess.invoke(page,response.data?.data)
//                                })

                        }

                        override fun onCallError(error: String?) {
                            super.onCallError(error)
                            actionError.invoke(page,error)
                        }
                    })
            }
        }
    }
    override fun initView(savedInstanceState: Bundle?) {
        setActivityTitle(getString(R.string.my_device_txt))
        homeBtn.apply {
            visibility = View.VISIBLE
            setImageResource(R.mipmap.my_device_add_icon)
            onClick {
                startActivity(Intent(this@MyDeviceActivity,BindDeviceActivity::class.java))
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(this)
        mAdapter = MyDeviceAdapter()
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val info = mAdapter.getItem(position)?:return@setOnItemChildClickListener
            when(view.id){
                R.id.right_view->{
                    (view.parent as? SwipeLayout)?.close(true)
                    MessageImageDialog.Builder(this)
                        .title(getString(R.string.confirm_remove_device_txt))
                        .content(getString(R.string.remove_device_on_list_txt))
                        .okClick {
                            OkGo.post<LzyResponse<Any>>(Constants.deleteFormRow)
                                .paramEx(mutableMapOf("rowid" to info.id,"formheaduuid" to "2582bc4c14914246807a26886f46dd0e"),true)
                                .tag(this)
                                .execute(object : SimpleHttpCallback<LzyResponse<Any>>(activity = this@MyDeviceActivity){
                                    override fun onCallSuccess(response: LzyResponse<Any>) {
                                        ToastUtils.show(getString(R.string.remove_success_txt))
                                        EventBus.getDefault().post(ChangeDeviceEvent())
//                                        mAdapter.remove(position)
                                        refreshLayoutDelegate.requestRefresh(false)
                                    }
                                })
                        }
                        .build()
                        .show()
                }
                else->{
//                    DeviceDetailActivity.start(this,info.bhmohipntdlpc61m)
                }
            }

        }
        recyclerView.adapter = mAdapter
        refreshLayoutDelegate.init(smartRefreshLayout,recyclerView,false)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChangeDeviceEvent){
        refreshLayoutDelegate.requestRefresh(true)
    }

    override fun isHaveEventBus(): Boolean {
        return true
    }

    override fun showEmptyView(emptyText: String) {
        statusLayoutManager?.showEmptyLayout2(
            ComplexSpannableStringUtils.getBuilder(getString(R.string.no_device_1_txt))
                .append(getString(R.string.no_device_2_txt))
                .setForegroundColor(ContextCompat.getColor(this,R.color.c_831cb5))
                .setClickSpan(NoRefCopySpan {
                    homeBtn.performClick()
                })
                .create()
        )
    }
}